import { BrowserWindow, app, nativeImage } from "electron";
import { getResPath } from "../util";
import injectGlobalData from "./common/inject-global-data";
import makeWindowFullyDraggable from "./common/make-window-fully-draggable";
import {
  getAppConfig,
  getAppConfigPath,
  setAppConfigPath,
} from "@/common/app-config/main";
import { registerExtension, unregisterExtension } from "../core/extensions";
import { ipcMainSend } from "@/common/ipc-util/main";
import { currentMusicInfoStore } from "../store/current-music";

// This allows TypeScript to pick up the magic constants that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const LRC_WINDOW_WEBPACK_ENTRY: string;
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;

/** 歌词窗口创建 */
let lyricWindow: BrowserWindow | null = null;

export const createLyricWindow = (): BrowserWindow => {
  // Create the browser window.
  const width = 920;
  const height = 160;
  lyricWindow = new BrowserWindow({
    height,
    width,
    transparent: true,
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      nodeIntegration: true,
      webSecurity: false,
      sandbox: false,
    },
    resizable: false,
    frame: false,
    skipTaskbar: true,
    alwaysOnTop: true,
    icon: nativeImage.createFromPath(getResPath('logo.png')),
  });

  // and load the index.html of the app.
  lyricWindow.loadURL(LRC_WINDOW_WEBPACK_ENTRY);

  if (!app.isPackaged) {
    // Open the DevTools.
    lyricWindow.webContents.openDevTools();
  }

  lyricWindow.webContents.on("did-finish-load", () => {
    injectGlobalData(lyricWindow);
  });

  makeWindowFullyDraggable(lyricWindow, {
    width,
    height,
    onMouseUp(position) {
      if (position) {
        setAppConfigPath("private.lyricWindowPosition", {
          x: position.x,
          y: position.y,
        });
      }
    },
  });

  // 初始化设置
  lyricWindow.once("ready-to-show", async () => {
    const position = await getAppConfigPath("private.lyricWindowPosition");
    if (position) {
      lyricWindow.setPosition(position.x, position.y, false);
    }
    const lockState = await getAppConfigPath("lyric.lockLyric");

    if (lockState) {
      lyricWindow.setIgnoreMouseEvents(true, {
        forward: true,
      });
    }
  });

  //   lyricWindow.setIgnoreMouseEvents(true, {
  //     forward: true
  //   })
  registerExtension(lyricWindow);
  return lyricWindow;
};

export const closeLyricWindow = () => {
  unregisterExtension(lyricWindow);
  lyricWindow?.close();
  lyricWindow = null;
};

export const getLyricWindow = () => lyricWindow;
